'''
Copyright: 
Descripttion: 
version: 
Author: chengx
Date: 2021-05-27 10:35:28
LastEditors: chengx
LastEditTime: 2021-05-30 14:36:51
'''
# -*-coding=utf-8 -*-
from operator import mod
from sklearn.svm import SVC
import numpy as np
import scipy.signal
import scipy.io as sio
import random
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
import spectral
import cv2

# # 加载数据
def creatData():
    x = scipy.io.loadmat('./HSI/PaviaU.mat')['paviaU']
    y = scipy.io.loadmat('./HSI/PaviaU_gt.mat')['paviaU_gt']

    x = np.reshape(x,(x.shape[0]*x.shape[1],x.shape[2]))
    y = y.reshape(y.shape[0]*y.shape[1])

    pos = np.where(y==0)
    y = np.delete(y,pos)
    x = np.delete(x,pos,axis=0)
    print('read hsi shape is',x.shape,y.shape)
    # # 按行归一化
    # for i in range(x.shape[1]):
    #     fm = np.max(x[:,i])-np.min(x[:,i])
    #     x[:,i] = (x[:,i] - float(np.min(x[:,i])))
    #     x[:,i] = x[:,i]/fm

    return x,y

def split_train_test_set(x, y, test_ratio, random_state=10):

    x_train, x_test, y_train, y_test = train_test_split(x,
                                                        y,
                                                        test_size=test_ratio,
                                                        random_state=random_state,
                                                        stratify=y)

    return x_train, x_test, y_train, y_test

def train(train,train_label):
    # SVM配置拟合
    clf = SVC(C=1000)#,gamma=1
    clf.fit(train,train_label)
    return clf

def test(model,test,test_label):
    y_pred = model.predict(test)
    # M = metrics.confusion_matrix(test_label,y_pred)
    # print(M)
    OA = accuracy_score(test_label, y_pred)
    return OA

def creatResultImage(im,imGIS,model):
    """
    Parameters: im : 未处理的原图
                imGIS: 标签 
                model: 预测模型
    Description: 预测每一个点
    Returns: None
    """
    iG = np.zeros((imGIS.shape[0],imGIS.shape[1]))
    for i in range(imGIS.shape[0]):
        for j in range(imGIS.shape[1]):
            if imGIS[i,j] == 0:
                    iG[i,j]=0
            else:
                iG[i,j] = (model.predict(im[i,j].reshape(-1,len(im[i,j]))))

    drawPic(iG) # 生成伪彩图
    print('生成伪装彩图成功')



def drawPic(data):#上色
    """
    Parameters: data : 分类结果，numpy
    Description: 按data给点上色
    Returns: None
    """
    import random
    random.seed(5)
    r = random.sample(range(0,255),16)
    g = random.sample(range(0,255),16)
    b = random.sample(range(0,255),16)
    rgb = np.concatenate((r,g,b)).reshape(3,16)

    img =np.zeros((data.shape[0],data.shape[1],3))
    #平均点光谱,按区域上色,(b,g,r)
    for i in range(data.shape[0]):
        for j in range(data.shape[1]):
            if data[i][j] ==0:
                continue
            else:
                img[i,j,:]=rgb[:,int(data[i,j])]


    # img = cv2.transpose(img)#水平翻转+旋转
    cv2.imwrite('./rgb.jpg',img)

def svmRun(x,y,index):
    ratio = 0.8 #测试数据占总数据的比例
    if index.sum() == 0:
        pass
    else:
        x = x[:,index]
    x_train, x_test, y_train, y_test = split_train_test_set(x,y,test_ratio =ratio,random_state=1)
    model = train(x_train,y_train)
    OA = test(model,x_test,y_test)

    return OA,model


if __name__ == '__main__':
    
    ratio = 0.8 #测试数据占总数据的比例
    x,y = creatData()
    x_train, x_test, y_train, y_test = split_train_test_set(x,y,test_ratio =ratio,random_state=1)
    model = train(x_train,y_train)
    OA = test(model,x_test,y_test)

